<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
import { downLoadMix } from '@/utils/export-util/util'
import { downFile, downFilePost } from '@/api/manage'

export default {
  data() {
    return {
      loading: false
    }
  },
  props: {
    apiUrl: {
      type: String,
      default: ''
    },
    formData: {
      type: Object
    },
    fileText: {
      type: String,
      default: ''
    }
  },
  watch: {
    loading: {
      handler(bool) {
        this.$emit('queryMethod', bool)
      },
      // 代表在wacth里声明了这个方法之后立即先去执行handler方法
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 下载文件流,get方式
    async exportDowm() {
      this.loading = true
      downFile(this.apiUrl, this.formData)
        .then(res => {
          this.loading = false
          downLoadMix(res, this.fileText)
        })
        .catch(e => {
          this.loading = false
        })
        .finally(() => (this.loading = false))
    },
    // 下载文件流,post方式
    async exportDowmPOST() {
      this.loading = true
      downFilePost(this.apiUrl, this.formData)
        .then(res => {
          this.loading = false
          downLoadMix(res, this.fileText)
        })
        .catch(e => {
          this.loading = false
        })
        .finally(() => (this.loading = false))
    },
    // 下载文件改名
    //url:文件地址 filename:想要修改为的名称
    downloadFile(url, filename) {
      let that = this
      this.getBlob(url, function(blob) {
        that.saveAs(blob, filename)
      })
    },
    getBlob(url, cb) {
      let that = this
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url, true)
      xhr.responseType = 'blob'
      xhr.onload = function() {
        if (xhr.status === 200) {
          that.$emit('downLoadComplete')
          cb(xhr.response)
        }
      }
      xhr.send()
    },
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename)
      } else {
        var link = document.createElement('a')
        var body = document.querySelector('body')
        link.href = window.URL.createObjectURL(blob)
        link.download = filename
        link.style.display = 'none'
        body.appendChild(link)
        link.click()
        body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
      }
    }
  }
}
</script>
